<?php
/*
分类组件
*/
class Com_cg{
	
	function __construct($ainfo=null){
		$this->cg_dbname = Acan_table_cg;
		if($ainfo){
			$this->cg_dbname = Acan_table_cg.'_'.$ainfo;
		}
		$this->cg = Afun_db()->model($this->cg_dbname);
		$this->cache_name = $this->cg_dbname.'/';
	}
	function array_cg($pid=1,$uid="",$cgrr=""){
		if ($cgrr) {
			if(is_string($cgrr)){
				$cgrr = explode('-',$cgrr);
			}
			$data->val = $cgrr[0];
			unset($cgrr[0]);
			foreach ($cgrr as $k => $v) {$cgrrs[] = $v;}
		}else{
			$cgrr = '';
		}
		$model = $this->cgdata($pid,$uid);
		if(!is_array($model)){return;}
		$data->arr[''] = '默认';
		foreach ($model as $key => $val) {
			$data->arr[$val->value] = $val->cgname;
			if(is_array($val->child)){
				if($val->value != $data->val){
					$cgrrs = '';
				}
				$data->child[$val->value] = $this->array_cg($val->id,$uid,$cgrrs);
			}
		}
		return $data;
	}
	function obj_arr($model){
		foreach ($model as $key => $val) {
			$data[$val->value] = $val->cgname;
		}
		return $data;
	}
	function arrays($model){
		foreach ($model as $key => $val) {
			$data[$val['value']] = $val['cgname'];
		}
		return $data;
	}
	//获取所有分类并缓存
	function cgdata($pid=1,$uid=""){
		$this->cache_name .= $pid.'_'.$uid;
		$data = Afun_cache_get($this->cache_name);
		if(empty($data)){
			$data = $this->cgdatas($pid,$uid);
			Afun_cache_set($this->cache_name,$data);//写入缓存
		}
		return $data;
	}
	//递归获取子分类(返回对象)
	function cgdatas($pid=1,$uid=""){
		$con->where = "pid = $pid";
		if($uid){$con->where .= " and uid = $uid";}
		$model = $this->cg->findAll($con);
		if(empty($model)){return ;}
		$i = 0;
		foreach ($model as $k => $v) {
			$data[$i]->id = $v['id'];
			$data[$i]->pid = $v['pid'];
			$data[$i]->name = $v['name'];
			$data[$i]->cgname = $v['cgname'];
			$data[$i]->value = $v['value'];
			$child = $this->cgdatas($v['id'],$uid);
			if($child && $pid == 1){
			//	$data[$i]->arr = $this->arrays($model);
			//	$data[$i]->child_arr = $this->obj_arr($child);
			}
			$data[$i]->child = $child;
			$i++;
		}
		return $data;
	}
	
	//根据id,name获取分类信息
	function model($name='',$pid='1',$uid=''){
		if(is_int($name)){
			return $this->cg->ofindPk($name);
		}
		$con->where = "a.pid = $pid";
		if($name){
			$con->where .= " and a.name = '$name'";
		}
		if($uid){
			$con->where .= " and a.uid = '$uid'";
		}
		return $this->cg->ofind($con);
	}
	function cgbyname($name,$uid=''){
		$nrr = explode('-',$name);
		foreach($nrr as $k=>$v){
			if(empty($cg)){
				$model = $this->model($v,1,$uid);
				$cg = $model->value;
			}else{
				$model = $this->model($v,$model->id,$uid);
				$cg .= '-'.$model->value;
			}
		}
		return $cg;
	}
	function group(){
		$pid = $this->model('group')->id;
		$data = $this->cgdatas($pid);
		print_r($data);
	}
}

?>